package eiisan.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用CyclicBarrier例子：所有线程完成后进行结果汇总操作
 * @author eii
 * @time 2020/10/30 9:52 下午
 */
public class CyclicBarrierTest {

    //创建一个CyclicBarrier实例，添加一个所有子线程全部到达屏障后执行任务
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2,()->{
        System.out.println(Thread.currentThread() + "All Task merge result enter");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + "All Task merge result outer");
    });

    public static void main(String[] args) {
        //创建一个线程固定个数为2的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + "Task1 - 1");
                System.out.println(Thread.currentThread() + "Task1 enter in Barrier");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "Task1 outer in Barrier");
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + "Task1 - 2");
                System.out.println(Thread.currentThread() + "Task2 enter in Barrier");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "Task2 outer in Barrier");
            }
        });

        executorService.shutdown();
    }
}
